package transfer

import (
	"errors"
	"fmt"
	"net"
)

// 默认最大长度20M
const DefaultMaxLength = uint32(1024 * 1024 * 20)

// 从连接中读取数据，不判断最大长度
func ReadConn(
	conn net.Conn,
	length uint32,
) (buf []byte, err error) {
	return ReadConnMaxLength(conn, length, 0)
}

// 从连接中读取数据，判断最大长度
func ReadConnMaxLength(
	conn net.Conn,
	length uint32,
	maxLength uint32,
) (buf []byte, err error) {
	if conn == nil {
		err = errors.New("连接不能为空")
		return
	}
	if maxLength > 0 && length > maxLength {
		err = fmt.Errorf("数据长度过大，疑似包传输异常")
		return
	}
	buf = make([]byte, length)
	start := 0
	for {
		cnt, e := conn.Read(buf[start:])
		if e != nil {
			err = e
			return
		}
		if cnt > 0 {
			start += cnt
		} else {
			return
		}
	}
}
